<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="11" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入11"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="123" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入123"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="1231" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入1231"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
         
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
         
        >导出excel</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="uploadDialogVisible = true"
        >导入文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExportword"
        >导出word</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExportpdf"
        >导出pdf</el-button>
      </el-col>
    </el-row>

    <!-- 导入文件对话框 -->
    <el-dialog 
      :title="'导入文件'" 
      v-model="uploadDialogVisible" 
      width="400px"  
      @close="handleUploadDialogClose"
    >
      <el-upload
        ref="uploadComponent"
        class="upload-demo"
        drag
        :multiple="true"  
        accept=".xls,.xlsx"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :http-request="customUploadRequest"
        size="mini"
      >
        <el-row :span="24" style="display: flex; align-items: center; justify-content: center; flex-direction: column;">
          <el-col :span="6">
            <el-icon style="margin-top: 25px" class="el-icon--upload"><UploadFilled /></el-icon>
          </el-col>
          <el-col :span="18">
            <p style="font-weight: 700;font-size: 20px">上传</p>
            <div class="el-upload__text">
              将文件拖到此处或者点击<em>上传文件</em>
            </div>
          </el-col>
        </el-row>
      </el-upload>
      <template #footer>  <!-- 替换slot="footer"为#footer -->
        <el-button @click="uploadDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-table 
  v-loading="loading" 
  :data="usList" 
  @selection-change="handleSelectionChange"
  :height="tableHeight"
  :max-height="tableMaxHeight"
>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" align="center" prop="id" />
      <el-table-column label="11" align="center" prop="name" />
      <el-table-column label="123" align="center" prop="age" />
      <el-table-column label="1231" align="center" prop="nickname" />
      <el-table-column label="img" align="center" prop="imgurl" >
        <!-- 替换slot-scope为#default -->
        <template #default="scope">
          <div v-if="scope.row.imgurl" class="image-preview">
            <el-image
              :src="scope.row.imgurl"
              fit="cover"
              style="width: 50px; height: 50px; border-radius: 4px;"
              :preview-src-list="[scope.row.imgurl]"
              lazy
            >
              <template #error>  <!-- 替换slot="error"为#error -->
                <div class="image-error">
                  <el-icon><PictureOutline /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          <div v-else class="no-image">
            <el-icon><PictureOutline /></el-icon>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:us:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:us:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
  v-show="total > 0"
  :total="total"
  v-model:current-page="queryParams.pageNum"
  v-model:page-size="queryParams.pageSize"
  layout="total, sizes, prev, pager, next, jumper"
  :page-sizes="[10, 20, 50, 100]"
  @size-change="handleSizeChange"
  @current-change="handleCurrentChange"
  background
/>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="11" prop="name">
          <el-input v-model="form.name" placeholder="请输入11" />
        </el-form-item>
        <el-form-item label="123" prop="age">
          <el-input v-model="form.age" placeholder="请输入123" />
        </el-form-item>
        <el-form-item label="1231" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入1231" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Us">
import { listUs, getUs, delUs, addUs, updateUs,exportWord,exportexcel,exportpdf,upfile } from "@/api/us"
import { getCurrentInstance, toRefs, reactive ,ref} from "vue"

const { proxy } = getCurrentInstance()

const usList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 添加到变量声明部分
const tableHeight = ref(window.innerHeight - 300);
const tableMaxHeight = ref(window.innerHeight - 200);
const uploadDialogVisible = ref(false)

import { ElMessage } from 'element-plus'

// 在变量声明部分添加缺失的响应式变量
const uploadedFiles = ref([])  // 存储已上传文件的列表
const uploadComponent = ref(null)  // 上传组件的引用
const updloadfileMessage = ref('')  // 上传文件消息
const uploadSuccessMessage = ref(false)  // 上传成功消息状态
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    age: null,
    nickname: null
  },
  rules: {
    name: [
      { required: true, message: "11不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)


// 上传前校验
const beforeUpload = (file) => {
  const isLxls = file.name.endsWith('.xls') || file.name.endsWith('.xlsx');
  const isSizeValid = file.size / 1024 / 1024 < 10;  // 限制10MB
  if (!isLxls) {
    ElMessage.error('请上传后缀名为.xls或.xlsx的文件');
    return false;
  }
  if (!isSizeValid) {
    ElMessage.error(`文件大小超过10MB限制，当前为${(file.size / 1024 / 1024).toFixed(2)}MB`);
    return false;
  }
  return true;
};

// 上传成功处理
const handleUploadSuccess = (response, file, fileList) => {
  ElMessage.success('文件上传成功');
  uploadedFiles.value.push({ name: file.name });
  if (fileList.length > 0) {
    uploadComponent.value.clearFiles();  // 清空显示
  }
};

// 自定义上传请求
const customUploadRequest = (option) => {
  const formData = new FormData();
  formData.append('file', option.file);
  upfile(formData).then(response => {
    updloadfileMessage.value = response.msg;
    uploadSuccessMessage.value = true;
    getList();
    // getUniqueData();  // 若有此方法需定义
  }).catch(error => {
    option.onError(error);
  });
};

// 关闭上传对话框
const handleUploadDialogClose = () => {
  if (uploadComponent.value) {
    uploadComponent.value.clearFiles();
  }
};


function handleSizeChange(newSize) {
  queryParams.value.pageSize = newSize
  getList()
}

// 处理当前页变化
function handleCurrentChange(newPage) {
  queryParams.value.pageNum = newPage
  getList()
}
/** 查询用户列表 */
function getList() {
  loading.value = true
  listUs(queryParams.value).then(response => {
    console.log(response)
    usList.value = response.data.rows
    total.value = response.data.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    age: null,
    nickname: null
  }
  proxy.resetForm("usRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加用户"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getUs(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改用户"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateUs(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUs(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除用户编号为"' + _ids + '"的数据项？').then(function() {
    return delUs(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// /** 导出按钮操作 */
// function handleExport() {
//   proxy.download('system/us/export', {
//     ...queryParams.value
//   }, `us_${new Date().getTime()}.xlsx`)
// }

getList()

async function handleExport() {
  const param = {};  // 可添加查询参数
  try {
    const response = await exportexcel(param);
    
    // 正确访问响应头
    const contentType = response.headers['content-type'] || '';
    
    // 检查返回的是否是JSON错误信息
    if (contentType.includes('application/json')) {
      // 如果是JSON，则直接解析（假设response.data已经是解析后的对象）
      ElMessage.error(`导出失败：${response.data.error || '未知错误'}`);
      return;
    }
    
    // 下载文件
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'users.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出异常:', error);
    ElMessage.error('导出失败，请检查网络或参数');
  }
}

// 导出Word
async function handleExportword(){
  const param = {};
  try {
    const response = await exportWord(param);
    const contentType = response.headers['content-type'];
    if (contentType.includes('application/json')) {
      const text = await new Blob([response.data]).text();
      const error = JSON.parse(text);
      ElMessage.error(`导出失败：${error.error}`);
      return;
    }
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'users.docx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出异常:', error);
    ElMessage.error('导出失败，请检查网络或参数');
  }
}

// 导出PDF
async function  handleExportpdf(){
  const param = {};
  try {
    const response = await exportpdf(param);
    const contentType = response.headers['content-type'];
    if (contentType.includes('application/json')) {
      const text = await new Blob([response.data]).text();
      const error = JSON.parse(text);
      ElMessage.error(`导出失败：${error.error}`);
      return;
    }
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'users.pdf';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出异常:', error);
    ElMessage.error('导出失败，请检查网络或参数');
  }
}

</script>
